package com.example.dense_rack_server.excel;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.context.xlsx.DefaultXlsxReadContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.dense_rack_server.Application;
import com.example.dense_rack_server.WebSocket.WebSocketServer;
import com.example.dense_rack_server.entity.*;
import com.example.dense_rack_server.mapper.*;
import com.example.dense_rack_server.security.dto.JwtUserDto;
import com.example.dense_rack_server.utils.DateFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 批量上传表格模板解析
 */
@Slf4j
public class ArchivesBatchListener extends AnalysisEventListener<ArchivesBatchImport> {
    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(ArchivesBatchImport data, AnalysisContext context) {
        System.out.println("解析到一条数据:" + JSON.toJSONString(data));
        Integer currentRowNum = ((DefaultXlsxReadContext) context).readSheetHolder().getRowIndex();
        // 静态方法注入bean解决方案
        ArchivesMapper archivesMapper = Application.ac.getBean(ArchivesMapper.class);
        ArchivesAreaMapper archivesAreaMapper = Application.ac.getBean(ArchivesAreaMapper.class);
        ArchivesTypeMapper archivesTypeMapper = Application.ac.getBean(ArchivesTypeMapper.class);
        HostMapper hostMapper = Application.ac.getBean(HostMapper.class);
        BorrowingRecordsMapper borrowingRecordsMapper = Application.ac.getBean(BorrowingRecordsMapper.class);
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = Convert.toStr(jwtUserDto.getMyUser().getUserId());

        // 确认文件名是否存在
        String fileName = data.getFileName();
        Archives archivesDb = archivesMapper.selectOne(new QueryWrapper<Archives>()
                .eq("file_name", fileName));
        if (archivesDb != null) {
            log.error("文件名已存在：" + fileName);
            try {
                WebSocketServer.sendInfo("第" + currentRowNum + "行，档案名已存在：" + fileName, userId);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        // 确认装具是否存在
        String fileId = data.getFileId();
        Archives archivesFileId = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("file_id", fileId));
        if (archivesFileId != null) {
            log.error("文件id已存在：" + fileId);
            try {
                WebSocketServer.sendInfo("第" + currentRowNum + "行，档案id已存在：" + fileId, userId);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        // 确认区域是否存在
        String areaName = data.getAreaName();
        ArchivesArea archivesArea = archivesAreaMapper.selectOne(new QueryWrapper<ArchivesArea>()
                .eq("area_name", areaName));
        if (archivesArea == null) {
            log.error("区域不存在：" + areaName);
            try {
                WebSocketServer.sendInfo("第" + currentRowNum + "行，库房不存在：" + areaName, userId);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        // 确认类型是否存在
        String typeName = data.getTypeName();
        ArchivesType archivesType = archivesTypeMapper.selectOne(new QueryWrapper<ArchivesType>()
                .eq("type_name", typeName));
        if (archivesType == null) {
            log.error("类型不存在：" + typeName);
            try {
                WebSocketServer.sendInfo("第" + currentRowNum + "行，档案类型不存在：" + typeName, userId);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        // 确认载体是否存在
        String cabinetName = data.getCabinetName();
        Host host = hostMapper.selectOne(new QueryWrapper<Host>().eq("cabinet_name", cabinetName));
        if (host == null) {
            log.error("载体不存在：" + data.getCabinetName());
            try {
                WebSocketServer.sendInfo("第" + currentRowNum + "行，载体不存在：" + data.getCabinetName(), userId);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        // 保存数据
        Archives archives = new Archives();
        archives.setFileId(fileId);
        archives.setFileName(fileName);
        if (StrUtil.isNotEmpty(data.getYear())) {
            archives.setYear(data.getYear());
        } else {
            Date date = DateUtil.date();
            archives.setYear(Convert.toStr(DateUtil.year(date)));
        }
        archives.setUserName(data.getUserName());
        archives.setProfile("");
        archives.setStatus(0);
        archives.setElectronFileStatus(0);
        archives.setArchivesAreaId(archivesArea.getId());
        archives.setArchivesTypeId(archivesType.getId());
        archives.setCreateTime(DateFormat.getTime());
        archives.setUpdateTime(DateFormat.getTime());
        archives.setAreaCode(host.getCabinetNumber());
        archives.setColumnNumber(data.getColumnNumber());
        if (data.getDenseRackRegion().equals("左区")) {
            archives.setDenseRackRegion(0);
        } else {
            archives.setDenseRackRegion(1);
        }
        archives.setJoint(data.getJoint());
        archives.setLayerNumber(data.getLayerNumber());
        archives.setPosition(data.getPosition());
        if (StrUtil.isNotEmpty(data.getUuid())) {
            archives.setUuid(data.getUuid());
        }else {
            archives.setUuid(IdUtil.simpleUUID());
        }
        archivesMapper.insert(archives);

        // 新增档案日志
        String userName = jwtUserDto.getUsername();
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileId(archives.getId());
        borrowingRecords.setFileName(archives.getFileName());
        borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
        borrowingRecords.setUserName(userName);
        borrowingRecords.setRemarks("");
        borrowingRecords.setCreateTime(DateFormat.getTime());
        borrowingRecords.setDataStatus(5);
        borrowingRecords.setStatus(1);
        borrowingRecords.setModuleType(2);
        borrowingRecords.setOperation(userName + "用户新增" + archives.getFileName() + "档案");
        borrowingRecords.setHostId(host.getId());
        borrowingRecordsMapper.insert(borrowingRecords);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }


}

